<template>
  <div class="ziru-con">
    <baidu-map
      class="bm-view"
      :center="'上海'"
      :zoom="zoom"
      :scroll-wheel-zoom="true"
      @ready="handler"
    >
      <bm-marker
        v-if="showEnd"
        :position="end"
        :dragging="true"
        animation="BMAP_ANIMATION_BOUNCE"
      >
        <bm-label
          content="三门路"
          :labelStyle="{ color: 'red', fontSize: '12px' }"
          :offset="{ width: -4, height: 30 }"
        />
      </bm-marker>

      <bm-marker
        v-for="(item, i) in points"
        :key="i"
        :position="item"
        :dragging="false"
        @click="handleClick(item)"
      >
        <bm-label
          :content="item.community + '/' + item.price + '/' + item.avgArea"
          :labelStyle="{ color: 'red', fontSize: '12px' }"
          :offset="{ width: -50, height: 30 }"
        />
      </bm-marker>

      <bm-info-window
        :show="showPoint"
        :position="curPoint"
        @close="showPoint = false"
      >
        <div>
          {{ curPoint.community }}
        </div>
        <div>房源数量: {{ curPoint.num }}套</div>
        <div>平均房租: {{ curPoint.price }}/套</div>
        <div>平均房租: {{ curPoint.avgArea }}/平米</div>
      </bm-info-window>

      <bm-local-search
        v-show="results.length"
        class="search-result"
        :keyword="keyword"
        :auto-viewport="true"
        location="上海"
        :panel="true"
        @markersset="resultshtmlset"
      ></bm-local-search>
      <bm-marker
        v-if="showStart"
        :position="start"
        :dragging="true"
        animation="BMAP_ANIMATION_BOUNCE"
      >
        <bm-label
          :content="curStation.station"
          :labelStyle="{ color: 'red', fontSize: '12px' }"
          :offset="{ width: -4, height: 30 }"
        />
      </bm-marker>

      <bm-bus
        class="bus-con"
        keyword="10"
        :auto-viewport="true"
        :selectFirstResult="true"
        :autoViewport="true"
        location="上海"
        @markersset="markersset"
      ></bm-bus>

      <bm-walking
        v-if="curPoint.lat"
        class="walk-con"
        :start="curPoint"
        :end="end"
        :auto-viewport="true"
        location="上海"
      ></bm-walking>

      <bml-heatmap :data="points" :max="3000" :radius="20"> </bml-heatmap>
    </baidu-map>
    <div class="search-con">
      <Input
        v-model="keyword"
        clearable
        placeholder="请输入关键字..."
        style="width: 200px"
        @on-change="handleChange"
      />
      <Button type="primary" style="margin-left: 10px">确定</Button>
    </div>
    <div class="table-con" v-show="tableData.length">
      <Table
        :loading="loading"
        row-key="id"
        border
        :columns="columns"
        :data="tableData"
        height="300"
        :load-data="handleLoadData"
      ></Table>
    </div>
  </div>
</template>

<script>
// import _ from "lodash";
import { commonApi } from "@/api/index";
import { BmlHeatmap } from "vue-baidu-map";
export default {
  data() {
    return {
      curPoint: {},
      showPoint: false,
      showRes: false,
      results: [],
      loading: false,
      showStart: false,
      showEnd: false,
      keyword: "",
      curStation: null,
      stationMap: {},
      columns: [
        // {
        //   title: "地铁站名",
        //   key: "station",
        //   tree: true,
        // },
        // {
        //   title: "房子数量",
        //   key: "len",
        // },
        // {
        //   title: "平均房租",
        //   key: "avgPrice",
        // },

        // {
        //   title: "平均房租/m2",
        //   key: "avgPrice2",
        // },
        {
          title: "房子标题",
          key: "name"
        },
        {
          title: "小区名称",
          key: "community"
        },
        {
          title: "房租",
          key: "price"
        },
        {
          title: "面积",
          key: "area"
        },
        {
          title: "平台",
          key: "platform"
        },
        {
          title: "详情",
          key: "id",
          render: (h, params) => {
            return params.row.name ? (
              <Button
                type="text"
                on-click={() => {
                  let url = params.row.detail.replace("https:", "");
                  console.log(url);
                  window.open(`https:${url}`);
                }}
              >
                详情
              </Button>
            ) : (
              ""
            );
          }
        }
      ],
      tableData: [],
      zoom: 11,
      BMap: null,
      start: null,
      end: {
        lat: 31.318782,
        lng: 121.514595
      },
      map: {},
      points: []
    };
  },
  components: {
    BmlHeatmap
  },
  mounted() {},
  methods: {
    handleClick(point) {
      this.showPoint = true;
      console.log(point);
      this.curPoint = point;
      setTimeout(() => {
        this.curPoint = point;
        this.showPoint = true;
      }, 300);

      commonApi({
        url: "/ziru/find",
        method: "post",
        data: {
          query: {
            community: point.community
          }
        }
      }).then(res => {
        console.log(res);
        this.tableData = res;
      });
    },
    handleChange({ value }) {
      if (!value) {
        this.results = [];
        this.showRes = false;
      }
    },
    handleRowClick(data) {
      console.log(data);
      if (data.community) {
        this.keyword = data.community;
      } else {
        this.start = this.stationMap[data.station]
          ? this.stationMap[data.station].point
          : null;
        this.curStation = data;
        this.showStart = true;
        this.showEnd = true;
      }

      // this.keyword = data.community;
    },
    handler({ BMap, map }) {
      this.BMap = BMap;
      this.map = map;
      console.log(BMap, map);
    },
    resultshtmlset(points) {
      console.log(this.keyword, points);
      // if (points && points.length) {
      //   commonApi({
      //     url: "/ziru/setPoint",
      //     method: "post",
      //     data: {
      //       community: this.keyword,
      //       ...points[0].point,
      //     },
      //   });
      // }
    },
    getTreeData(item, data, callback) {
      data.forEach(child => {
        if (child.id == item.id) {
          let res = [];
          child.children.forEach(item2 => {
            let tempData = JSON.parse(JSON.stringify(item2));
            if (tempData.children && tempData.children.length) {
              tempData.children = [];
              tempData._loading = false;
            } else {
              tempData.children = null;
            }
            res.push(tempData);
          });
          callback(res);
        }
        if (child.children && child.children.length) {
          this.getTreeData(item, child.children, callback);
        }
      });
    },
    handleLoadData(item, callback) {
      this.getTreeData(item, this.fullData, callback);
    },
    markersset() {
      this.getCommunities();
      // this.loading = true;
      // let index = 0;
      // for (let i = 0; i < arr.length; i++) {
      //   if (arr[i].RB === "三门路") {
      //     index = i;
      //   }
      // }
      // let sIndex = index - 1;
      // let eIndex = index + 1;
      // for (let i = 0; i < 10; i++) {
      //   if (sIndex > 0) {
      //     sIndex -= 1;
      //   }
      //   if (eIndex < arr.length - 1) {
      //     eIndex += 1;
      //   }
      // }
      // console.log(index, sIndex, eIndex);
      // let res = arr.slice(sIndex, eIndex);
      // res.forEach((item) => {
      //   this.stationMap[item.RB] = item;
      // });
      // console.log(this.stationMap);
      // let names = res.map((item) => item.RB);
      // commonApi({
      //   url: "/ziru/getResults",
      //   method: "post",
      //   data: {
      //     names,
      //   },
      // }).then((res) => {
      //   let list = [];
      //   for (let key in res) {
      //     let sum = 0;
      //     let areaSum = 0;
      //     let obj = {
      //       id: key,
      //       station: key,
      //       len: res[key].length,
      //       children: res[key],
      //     };
      //     for (let i = 0; i < res[key].length; i++) {
      //       sum += res[key][i].price;
      //       areaSum += res[key][i].area;
      //     }
      //     obj.avgPrice = sum / res[key].length;
      //     obj.avgPrice2 = sum / areaSum;
      //     list.push(obj);
      //   }
      //   this.fullData = list.sort((a, b) => a.avgPrice2 - b.avgPrice2);
      //   this.tableData = [];
      //   this.fullData.forEach((item) => {
      //     let tempData = JSON.parse(JSON.stringify(item));
      //     if (tempData.children && tempData.children.length) {
      //       tempData.children = [];
      //       tempData._loading = false;
      //     } else {
      //       tempData.children = null;
      //     }
      //     this.tableData.push(tempData);
      //   });
      //   this.loading = false;
      // });
    },
    sleep(time) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve();
        }, time);
      });
    },
    getCommunities() {
      commonApi({
        url: "/ziru/getStatistic",
        method: "get",
        data: {}
      }).then(res => {
        this.points = res;
        this.showEnd = true;
      });
    },
    async getLocation() {
      // for (let i = 0; i < this.list.length; i++) {
      //   this.keyword = this.list[i].community;
      //   console.log(this.keyword);
      //   await this.sleep(5000);
      // }
    }
  }
};
</script>

<style lang="scss" scoped>
.ziru-con {
  width: 100%;
  height: 100%;
  position: relative;
  .bm-view {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
  .bus-con {
    position: absolute;
    width: 20%;
    top: 0;
    right: 0;
  }
  .walk-con {
    position: absolute;
    height: 50%;
    overflow: auto;
    width: 20%;
    top: 0;
    right: 20%;
  }
  .table-con {
    position: absolute;
    width: 100%;
    height: 300px;
    bottom: 0;
    right: 0;
  }
  .search-con {
    width: 500px;
    position: absolute;
    top: 30px;
    left: 50px;
  }
  .search-result {
    position: absolute;
    width: 300px;
    top: 70px;
    left: 50px;
    background: white;
    border: 1px solid;
    .res-item {
      border-bottom: 1px solid;
      cursor: pointer;
      padding: 5px;
      &:hover {
        background: rgb(228, 226, 226);
      }
      &:last-child {
        border: none;
      }
      .title {
        color: blue;
      }
      .address {
        color: #777777fc;
      }
    }
  }
}
</style>
